import { app, BrowserWindow, ipcMain, dialog } from "electron";
import path, { join } from "path";

const fs = require('fs-extra');

var cmd = require('node-cmd');

let mainWin = null;

const createWindow = () => {
	mainWin = new BrowserWindow({
		width: 800,
		height: 600,
		maximizable: false,
		resizable: false,
		webPreferences: {
			preload: path.join(__dirname, "../preload/index.js"),
			nodeIntegration: true,
			contextIsolation: false
		},
	});

	if (app.isPackaged) {
		mainWin.loadFile(join(__dirname, "../../index.html"));
	} else {
		// 环境变量VITE_DEV_SERVER_HOST和VITE_DEV_SERVER_PORT在vite-plugin-electron插件中默认定义
		mainWin.loadURL(process.env['VITE_DEV_SERVER_URL']);
	}
};

app.whenReady().then(() => {
	createWindow();
	app.on("activate", () => {
		if (BrowserWindow.getAllWindows().length === 0) {
			createWindow();
		}
	});
});

app.on("window-all-closed", () => {
	if (process.platform !== "darwin") {
		app.quit();
	}
});

ipcMain.handle("select-output-path",() => {
	return dialog.showOpenDialog({ properties: ['openFile', 'openDirectory'] })
})

ipcMain.handle("isPackaged",() => {
	return app.isPackaged
})

ipcMain.handle("set-mainWin-large",() => {
	mainWin.setContentSize(1400,800);
	mainWin.center()
})

ipcMain.handle("set-mainWin-small",() => {
	mainWin.setContentSize(800,600);
	mainWin.center()
})

//预览单个demo页面
ipcMain.handle("open-child-window", (event) => {
	// let demoPath = path.join(__dirname, "../../../output/template/project")
	// const process = cmd.runSync(`cd ${demoPath} && npm run dev`)
	// console.log(process.pid);
	// return;
	
	const childWin = new BrowserWindow({
		width: 1280,
		height: 800,
		parent:mainWin,
		webPreferences: {
			preload: path.join(__dirname, "../preload/index.js"),
			nodeIntegration: true,
			contextIsolation: false
		},
	});
	if (app.isPackaged) {
		childWin.loadFile(join(__dirname, "../../index.html"));
		childWin.on("closed",async() => {
			//删除
			let path = join(__dirname,'../../../');
			console.log('path',path);
			const result = await fs.readFile(`${path}output/nowInfo.json`,'utf8');
    		let useResult = eval('(' + result + ')');
			useResult.isPreview = false;
			fs.writeJsonSync(`${path}output/nowInfo.json`, useResult)
		})
	}else{
		let previewPage = process.env['VITE_DEV_SERVER_URL'] + '#/preview';
		childWin.loadURL(previewPage);
	}
})

//预览示例工程
ipcMain.handle("preview-demo-project",() => {
	const demoWin = new BrowserWindow({
		width: 1280,
		height: 800,
		parent:mainWin,
		webPreferences: {
			preload: path.join(__dirname, "../preload/index.js"),
			nodeIntegration: true,
			contextIsolation: false
		},
	});
	//demoWin.loadURL("https://hanxuming.gitee.io/vite-base-pc/#/login");
	demoWin.loadFile(join(__dirname, "../../../output/template/preview/project/demo/index.html"));
})